package com.fh.shop.api.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.fh.shop.api.mq.config.MQConstant;
import com.fh.shop.api.mq.message.MailMessage;
import com.fh.shop.api.util.MailUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class MailConsumer {
    @Autowired
    private MailUtil mailUtil;

    @RabbitListener(queues = MQConstant.Mail.QUEUE)
    public void handleMailMessage(String msg, Message message, Channel channel) throws IOException {
        // 获取消息标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 处理业务
        try {
            MailMessage mailMessage = JSON.parseObject(msg, MailMessage.class);
            String mail = mailMessage.getMail();
            String title = mailMessage.getTitle();
            String content = mailMessage.getContent();
            mailUtil.sendMail(mail, title, content);
        } catch (Exception e) {
            log.error("处理邮件{}错误，原因为:{}", msg, e.getMessage());
            // 记录相关信息到数据库表中

        } finally {
            // 手动ack
            channel.basicAck(deliveryTag, false);
        }

    }
}
